package javango.forms.fields;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.google.inject.Inject;

import javango.forms.widgets.DateTimeWidget;
import javango.forms.widgets.DateWidget;
import javango.forms.widgets.WidgetFactory;

public class DateTimeField extends FieldBase {

	public static final String DATE_FORMAT = "MM/dd/yyyy HH:mm";
	
	public final DateFormat DATE_FORMATTER = new SimpleDateFormat(DATE_FORMAT);

	@Inject
	public DateTimeField(WidgetFactory factory) {
		super(factory);
		this.setWidget(DateTimeWidget.class);
	}
	
	@Override
	public Object clean(String value, Map<String, String> errors) {
		if (StringUtils.isBlank(value)) {
			if (!isRequired()) {
				return null;
			}
		} else {		
			try {
				return DATE_FORMATTER.parse(value);
			} catch (ParseException e) {
				errors.put(this.getName(), e.toString());
			}
		}
		
		return super.clean(value, errors);
	}

	
}
